package com.marvels.approve.loan.service.impl;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.util.StringUtil;
import com.marvels.approve.common.service.ApproveIStateDetailedService;
import com.marvels.approve.common.service.McamLoanApplyInfoCommonService;
import com.marvels.approve.loan.dto.LoanApprovalDTO;
import com.marvels.approve.loan.dto.McamLoanApplyInfoDTO;
import com.marvels.approve.loan.service.ILoanApprovalService;
import com.marvels.approve.loan.service.ILoanSamplingService;
import com.marvels.approve.loan.service.IMcamLoanApplyInfoService;
import com.marvels.approve.manager.dto.OpinionDTO;
import com.marvels.approve.manager.dto.OpinionTypeDTO;
import com.marvels.approve.manager.service.IOpinionService;
import com.marvels.approve.manager.service.IOpinionTypeService;
import com.marvels.approve.process.dao.ILoanApplyCaseDao;
import com.marvels.approve.process.dto.CompleteProcessDTO;
import com.marvels.approve.process.dto.LoanApplyCaseDTO;
import com.marvels.approve.process.dto.LoanApplyCaseLogDTO;
import com.marvels.approve.process.dto.ProcessApproveDTO;
import com.marvels.approve.process.service.ILoanApplyCaseLogService;
import com.marvels.approve.process.service.IProcessService;
import com.marvels.common.constants.CaseNodeConstant;
import com.marvels.common.constants.LoanStateConstant;
import com.marvels.common.dto.UserDTO;
import com.marvels.common.exception.MarvelsBusinessException;
import com.marvels.common.utils.CacheUtils;

@Service
public class LoanApprovalServiceImpl implements ILoanApprovalService {
	@Autowired
	private ILoanApplyCaseDao loanApplyCaseDao ;
	@Autowired
	private IOpinionTypeService opinionTypeService ;
	@Autowired
	private ILoanApplyCaseLogService loanApplyCaseLogService;
	@Autowired
	private IOpinionService opinionService;
	@Autowired
	private IMcamLoanApplyInfoService mcamLoanApplyInfoService;
	@Autowired
	private McamLoanApplyInfoCommonService mcamLoanApplyInfoCommonService;
	@Autowired
	private ILoanSamplingService loanSamplingService;
	@Autowired
	private IProcessService processService;
	@Autowired
	private ApproveIStateDetailedService stateDetailedService;
	@Override
	public LoanApprovalDTO findLoanApproval(LoanApprovalDTO loanApprovalRequest) throws MarvelsBusinessException {
		// TODO Auto-generated method stub
		// 查询征信阶段信息
		if (loanApprovalRequest == null || loanApprovalRequest.getLoanId() == null) {
			throw new MarvelsBusinessException("查询审批阶段信息条件不能为空" + loanApprovalRequest);
		}
		String loanId = loanApprovalRequest.getLoanId();
		LoanApplyCaseDTO loanApplyCase = loanApplyCaseDao.getEntityByLoanId(loanId);
		if (loanApplyCase == null) {
			throw new MarvelsBusinessException("工单不存在loanId:" + loanId);
		}
		if (!CaseNodeConstant.WOAPPROVAL.getCode().equals(loanApplyCase.getCurNodeCode())) {
			throw new MarvelsBusinessException("工单节点在" + loanApplyCase.getCurNodeCode() + "不正确,本次应该是审批,loanId:" + loanId);
		}
		UserDTO user = CacheUtils.getCacheUser();
		String userCode = user.getUserCode();
		if (userCode == null || !userCode.equals(loanApplyCase.getAssignee())) {
			throw new MarvelsBusinessException("工单属于" + loanApplyCase.getAssignee() + ",请确认工单所属,loanId:" + loanId);
		}
		loanApprovalRequest.setLoanApplyCase(loanApplyCase);
		// 初始化类型选项
		Map<Integer, List<OpinionTypeDTO>> opinionTypes = opinionTypeService.getOpinionTypes(CaseNodeConstant.WOAPPROVAL.getCode());
		loanApprovalRequest.setOpinionTypes(opinionTypes);
		
		//LOG
		List<OpinionDTO>  logs = opinionService.selectApproveResultLogByLoanId(loanApplyCase);
		loanApprovalRequest.setLogs(logs);
		//OPINOIN
		List<OpinionDTO> opinions = opinionService.selectOpinionsByCaseVersion(loanApplyCase);
		loanApprovalRequest.setOpinions(opinions);
		// 日志加意见
		return loanApprovalRequest;
	}

	@Override
	public LoanApprovalDTO saveLoanApproval(LoanApprovalDTO loanApprovalRequest) throws MarvelsBusinessException {
		//保存审批复核信息
		String loanId = loanApprovalRequest.getLoanId();
		LoanApplyCaseDTO loanApplyCase = getLoanApplyCase(loanId);
		McamLoanApplyInfoDTO loanApplyInfo = getLoanApplyInfo(loanId);
		//保存相关日志
//		 * @param loanApplyCase   流程管理对象
//		 * @param loanApplyInfo   进件数据
//		 * @param processOpinions   复核意见
//		 * @param violationOpinion  违例
//		 * @param returnAppOpinions  退单到前端APP类型
//		 * @param refuseOpinionTypes  拒绝代码
		
//		 * @param opinionContent  审批意见
//		 * @param violationOptionContent  违例
//		 * @param returnAppOpinionContent 退单到前端APP类型
//		 * @throws MarvelsBusinessException
		opinionService.saveOpinions(loanApplyCase,loanApplyInfo,loanApprovalRequest.getProcessResult() 
				,loanApprovalRequest.getProcessOpinions(),loanApprovalRequest.getViolationOpinion(),loanApprovalRequest.getReturnAppOpinions(),loanApprovalRequest.getRefuseOpinionTypes()
				,loanApprovalRequest.getOpinionContent(),loanApprovalRequest.getViolationOptionContent(),loanApprovalRequest.getReturnAppOpinionContent());
		return loanApprovalRequest;
	}
	private McamLoanApplyInfoDTO getLoanApplyInfo(String loanId) throws MarvelsBusinessException {
		// 查询贷款信息
		if (loanId == null) {
			throw new MarvelsBusinessException("查询贷款信息条件不能为空" + loanId);
		}
		McamLoanApplyInfoDTO loanApplyInfo = this.mcamLoanApplyInfoService.findMcamLoanApplyInfo(loanId);
		if (loanApplyInfo == null) {
			throw new MarvelsBusinessException("贷款信息不存在loanId:" + loanId);
		}
		if ( !LoanStateConstant.S00.equals(loanApplyInfo.getStatus()) && !LoanStateConstant.S01.equals(loanApplyInfo.getStatus()) ) {
			throw new MarvelsBusinessException("贷款信息状态不是审批复核阶段，请确认数据是否正确！status:"+loanApplyInfo.getStatus()+"\tloanId:" + loanId);
		}
		return loanApplyInfo;
	}
	private LoanApplyCaseDTO getLoanApplyCase(String loanId) throws MarvelsBusinessException {
		// 查询复核信息
		if (loanId == null) {
			throw new MarvelsBusinessException("查询征信阶段信息条件不能为空" + loanId);
		}
		LoanApplyCaseDTO loanApplyCase = loanApplyCaseDao.getEntityByLoanId(loanId);
		if (loanApplyCase == null) {
			throw new MarvelsBusinessException("工单不存在loanId:" + loanId);
		}
		if (!CaseNodeConstant.WOAPPROVAL.getCode().equals(loanApplyCase.getCurNodeCode())) {
			throw new MarvelsBusinessException("工单节点在" + loanApplyCase.getCurNodeCode() + "不正确,loanId:" + loanId);
		}
		return loanApplyCase;
	}
	@Override
	@Transactional(timeout = 30 ,rollbackFor=Exception.class)
	public LoanApprovalDTO complateLoanApproval(LoanApprovalDTO loanApprovalRequest) throws MarvelsBusinessException {
		// 保存复核征信复核信息
		String loanId = loanApprovalRequest.getLoanId();
		LoanApplyCaseDTO loanApplyCase = getLoanApplyCase(loanId);
		McamLoanApplyInfoDTO loanApplyInfo = getLoanApplyInfo(loanId);

		// 保存相关日志
		opinionService.saveOpinions(loanApplyCase,loanApplyInfo,loanApprovalRequest.getProcessResult() 
				,loanApprovalRequest.getProcessOpinions(),loanApprovalRequest.getViolationOpinion(),loanApprovalRequest.getReturnAppOpinions(),loanApprovalRequest.getRefuseOpinionTypes()
				,loanApprovalRequest.getOpinionContent(),loanApprovalRequest.getViolationOptionContent(),loanApprovalRequest.getReturnAppOpinionContent());

		// 流转activiti
		CompleteProcessDTO completeProcessDTO = new CompleteProcessDTO();
		completeProcessDTO.setLoanId(loanId);
		ProcessApproveDTO processApproveDto = new ProcessApproveDTO();
		processApproveDto.setProcessResult(loanApprovalRequest.getProcessResult());
		completeProcessDTO.setProcessApproveDto(processApproveDto);
		loanApplyCase = processService.completeLoanApplyCase(completeProcessDTO);
		// 更改进件数据
		modifyStatus(loanApplyInfo, loanApplyCase);
		return loanApprovalRequest;
	}
	
	//征信 状态流转
	private void modifyStatus(McamLoanApplyInfoDTO loanApplyInfo,LoanApplyCaseDTO loanApplyCase)throws MarvelsBusinessException {
		String status = loanApplyInfo.getStatus();
		String nextStatus = "";
		String curNodeCode = loanApplyCase.getCurNodeCode();
		String assignee = loanApplyCase.getAssignee();
		if(CaseNodeConstant.WOSAMPLING.getCode().equals(curNodeCode)) {
			if(StringUtil.isEmpty(assignee)) {
				nextStatus = LoanStateConstant.C01;
			}else {
				nextStatus = LoanStateConstant.C00;
			}
			mcamLoanApplyInfoCommonService.updateMcamLoanApplyInfoStatusByLoanId(loanApplyInfo.getLoanId(), nextStatus, status, null);
		}else if(CaseNodeConstant.WOINTERVIEW.getCode().equals(curNodeCode)) {
			nextStatus = LoanStateConstant.P01;
			loanSamplingService.generateAssureBx(loanApplyInfo.getLoanId());
			mcamLoanApplyInfoCommonService.updateMcamLoanApplyInfoStatusByLoanId(loanApplyInfo.getLoanId(), nextStatus, status, null);
		}else if(StringUtils.equals(CaseNodeConstant.WOCHECKING.getCode(), curNodeCode)){//退单到征信审批
			if(StringUtil.isEmpty(assignee)) {
				nextStatus = LoanStateConstant.Z00;
			}else {
				nextStatus = LoanStateConstant.Z01;
			}
			mcamLoanApplyInfoCommonService.updateMcamLoanApplyInfoStatusByLoanId(loanApplyInfo.getLoanId(), nextStatus, loanApplyInfo.getStatus(), null);
		}
	}

	//修改进件状态
	private void editLoanApplyInfo(McamLoanApplyInfoDTO loanApplyInfo , LoanApplyCaseDTO loanApplyCase) throws MarvelsBusinessException {
		String nodeCode = loanApplyCase.getCurNodeCode();
		//feign调用
		String stateId = stateDetailedService.queryStateDetailedByNodeCode(nodeCode);
		if(stateId == null) {
			throw new MarvelsBusinessException("新节点"+nodeCode+"无法获取进件节点号"+stateId);
		}
		String oldStatus = loanApplyInfo.getStatus();
		loanApplyInfo.setOldStatus(oldStatus);
		loanApplyInfo.setStatus(stateId);
		this.mcamLoanApplyInfoService.updateMcamLoanApplyInfoByLoanId(loanApplyInfo);
	}
}
